<template>
	<view>
		<!-- 搜索区域 -->
		<view class="search-wrap">
			<uni-search-bar radius="100" focus clearButton="auto" cancelButton="none" @input="onInput" @clear="clearSearch" />
		</view>
		<!-- 搜索建议区域 -->
		<uni-list v-if="key">
			<uni-list-item v-for="i in suggestList" :key="i.goods_id" :title="i.goods_name" link  :to="`/subpkg/goods_detail/goods_detail?goods_id=${i.goods_id}`"/>
		</uni-list>
		<!-- 搜索历史 -->
		<view v-else class="history">
			<view class="title">
				<text>搜索历史</text>
				<uni-icons @click="clear" type="trash" size="20"/>
			</view>
			<view class="history-item">
				<uni-tag class="tag" inverted v-for="(item,index) in historyList" :key="index" :text="item" type="success" @click="toGoodsList(item)" />
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name: 'Search',
		data() {
			return {
				suggestList: [],
				time: null,
				key: '',
				historyList: uni.getStorageSync('history') || []
			}
		},
		methods: {
			onInput(e) {
				this.key = e
				clearTimeout(this.time)
				this.time = setTimeout(async() => {
					if (e === '') return
					const { data: res } = await uni.$http.get('goods/qsearch', { query: e})
					this.suggestList = res.message
					const idx = this.historyList.indexOf(e)
					if (idx != -1) this.historyList.splice(idx, 1)
					this.historyList.unshift(e)
					uni.setStorageSync('history', this.historyList)
				}, 500)
			},
			clear() {
				this.historyList = []
				uni.removeStorageSync('history')
			},
			toGoodsList(item) {
				uni.navigateTo({
					url:"/subpkg/goods_list/goods_list?query=" + item
				})
			},
			clearSearch() {
				this.suggestList = []
			}
		}
	}
</script>

<style lang="scss">
.search-wrap {
	background-color: #c00000;
	position: sticky;
	top: 0;
	z-index: 999;
}
::v-deep .uni-list-item__content-title {
	width: 100%;
	display: inline-block;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}
.history {
	padding: 20rpx;
	.title { 
		display: flex;
		justify-content: space-between;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #ddd;
	}
	.history-item {
		display: flex;
		flex-wrap: wrap;
		margin-top: 15px;
		padding-left: 11rpx;
		.tag {
			margin-right: 10px;
			margin-bottom: 10px;
		}
	}
}
</style>
